package org.judking.CarKeeper.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Queue;

import org.judking.CarKeeper.R;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.speech.tts.TextToSpeech.OnInitListener;

public class VoiceService implements OnCompletionListener {
	private final Context context;
	private MediaPlayer mp;
	private List<VoiceType> queue;
	private volatile boolean isUndergo = false;
	
	public VoiceService(Context context)			{
		this.context = context;
		this.queue = Collections.synchronizedList(new ArrayList<VoiceType>());
	}
	
	public synchronized void addToQueue(VoiceType vt)		{
		this.queue.add(vt);
		if(isUndergo == false)		{
			isUndergo = true;
			begin(tryGetHeadAndRemove());
		}
	}
	
	private synchronized VoiceType tryGetHeadAndRemove()			{
		if(this.queue.size() > 0)		{
			VoiceType tmp = this.queue.get(0);
			this.queue.remove(0);
			return tmp;
		}
		return null;
	}
	
	private synchronized void begin(VoiceType vt)			{
		mp = MediaPlayer.create(context, vt.RESID);
		mp.start();
		mp.setOnCompletionListener(this);
	}

	@Override
	public synchronized void onCompletion(MediaPlayer arg0) {
		VoiceType tmp = tryGetHeadAndRemove();
		if(tmp == null)		{
			isUndergo = false;
			mp.release();
			mp = null;
		}
		else		{
			begin(tmp);
		}
	}
	
	
	
	public static class VoiceType			{
		public static final VoiceType SPEED_CRASH = new VoiceType(R.raw.car_speed_crash);
		public static final VoiceType COOLANT_HIGH = new VoiceType(R.raw.coolant_high); 
		public static final VoiceType COOLANT_LOW = new VoiceType(R.raw.coolant_low); 
		public static final VoiceType FUEL_LOW = new VoiceType(R.raw.fuel_low); 
		public static final VoiceType WARM_UP = new VoiceType(R.raw.warm_up); 
		
		public final int RESID;
		
		private VoiceType(int resid)		{
			this.RESID = resid;
		}

	}
}
